package net.xdclass.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import net.xdclass.config.OssConfig;
import net.xdclass.service.FileService;
import net.xdclass.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private OssConfig ossConfig;





    @Override
    public String uploadUserImg(MultipartFile file) {


        String accessKeyId = ossConfig.getAccessKeyId();
        String accessKeySecret = ossConfig.getAccessKeySecret();
        String bucketname = ossConfig.getBucketname();
        String endpoint = ossConfig.getEndpoint();

        //创建OSS对象
        OSS ossClient = new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);
        //获取原生文件名字
        String originalFilename = file.getOriginalFilename();
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        String floder = dtf.format(now);
        //瓶装路径，oss上储存路径，2021/1/1asdasa.jpg
        String fileName = CommonUtil.getUUID();
        //拓展名后缀
        String extension= originalFilename.substring(originalFilename.lastIndexOf("."));
        //拼装
        String newFileName="user/"+floder+"/"+fileName+extension;
        try {
            PutObjectResult putObjectResult = ossClient.putObject(bucketname, newFileName, file.getInputStream());
            if (putObjectResult!=null){

                String imgUrl="https://"+bucketname+"."+endpoint+"/"+newFileName;
                return imgUrl;
            }
        } catch (IOException e) {

            e.printStackTrace();
        }finally {
            //不关闭要造成内存泄漏
            ossClient.shutdown();
        }
        return null;
    }
}
